'use strict'

const { Shopping, Op } = require('../model');

let fn_product = async (ctx, next) => {
    let keyword = ctx.query.keyword || ''
    if (keyword) {
        let list = await Shopping.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { name: keyword },
                    { price: isNaN(keyword) ? 0 : keyword },
                    { supplier: keyword }
                ]
            },
            order: ['id']
        })
        ctx.body = list
    } else {
        let list = await Shopping.findAll({
            order: ['id']
        })
        console.log(list);
        ctx.body = list
    }
}
let fn_product_id = async (ctx, next) => {
    let id = ctx.request.params.id;
    let arr = await Shopping.findByPk(id);
    if (arr) {
        ctx.body = {
            code: 1000,
            data: arr,
            msg: '获取成功'
        }
    } else {
        ctx.body = {
            code: 400,
            data: null,
            msg: '没有找到'
        }
    }
}
let fn_post = (ctx, next) => {
    let obj = ctx.request.body;
    console.log(obj);
    if (obj) {
        let tmpObj = {
            name: obj.name,
            price: obj.price,
            supplier: obj.supplier
        };
        Shopping.create(tmpObj)
        ctx.body = {
            code: 1000,
            data: tmpObj,
            msg: '新增成功'
        }
    } else {
        ctx.body = {
            code: 400,
            data: null,
            msg: '数据验证不成功'
        }
    }
}
let fn_put = async (ctx, next) => {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    let shopping = await Shopping.findByPk(id);
    //Shopping.findByPk(id);
    if (shopping) {
        await Shopping.update(obj, {
            where: { id: id }
        });
        ctx.body = {
            code: 1000,
            data: shopping,
            msg: '修改成功'
        }
    } else {
        ctx.body = {
            code: 400,
            data: null,
            msg: '指定修改记录元素不存在'
        }
    }
}
let fn_delete = async (ctx, next) => {
    let id = ctx.request.params.id;
    let shopping = await Shopping.findByPk(id)
    if (shopping) {
        await Shopping.destroy({
            where: { id: id }
        })
        ctx.body = {
            code: 1000,
            data: { id: id },
            msg: '删除成功'
        }
    } else {
        ctx.body = {
            code: 1000,
            data: '',
            msg: '删除失败'
        }
    }
}

module.exports = {
    'get /product': fn_product,
    'get /product_id': fn_product_id,
    'post /product': fn_post,
    'put /product/:id': fn_put,
    'delete /product/:id': fn_delete,
}